package com.james.ex;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @ClassName: WebErrorLog
 * @Author: JamesWang
 * @Date: 2021/4/22 20:43
 * @Description:
 * @Version:1.0
 */
@RestControllerAdvice
@Slf4j
public class WebErrorLog {

    /**
     * 认证异常
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(AuthenticationException.class)
    public ResponseEntity<String> authenticationExHandler(HttpServletRequest request, AuthenticationException e) {
        // 记录日志
        String ip = request.getRemoteHost();
        log.error("此ip:{}登录失败,原因是:{}",ip,e.getMessage());
        return ResponseEntity.ok("登录失败，请重新登录");
    }

    /**
     * 运行时异常
     * 捕获自己及其子类的异常
     * 当异常处理器具有异常的时候 就会被具体的异常捕获
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> runtimeExHandler(RuntimeException e) {
        // sql报错了存在注入风险
        // 异常信息要收集起来
        log.error("运行时异常了{}",e.getMessage());
        return ResponseEntity.ok(e.getMessage());
    }

    /**
     * 方法参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResponseEntity<String> methodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder("数据校验异常原因是:");
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            sb.append("字段:" + fieldError.getField() + "," + fieldError.getDefaultMessage() + "!");
        }
        log.error("参数绑定失败{}",sb.toString());
        return ResponseEntity.ok("请求参数错误");
    }
}
